<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.employeeName" placeholder="业务员姓名" style="width: 150px;" class="filter-item" maxlength="32" @keyup.enter.native="handleFilter"/>
      <el-input v-model="listQuery.employeeNo" placeholder="工号" style="width: 150px;" class="filter-item" maxlength="11" @keyup.enter.native="handleFilter"/>
      <el-input v-model="listQuery.policyNo" placeholder="保单号" style="width: 150px;" class="filter-item" maxlength="32" @keyup.enter.native="handleFilter"/>
      <el-date-picker
        v-model="listQuery.startDate"
        type="date"
        placeholder="出单日期开始"/>
      <el-date-picker
        v-model="listQuery.endDate"
        type="date"
        placeholder="出单日期结束"/>

      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">{{ $t('table.search') }}</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">{{ $t('table.add') }}</el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">{{ $t('table.export') }}</el-button>
      <FileUpload color="#1890ff" btn-text="批量上传车险佣金" upurl="/finance/commission/batch/commission/create" size="medium" class="editor-upload-btn" @successCBK="fileSuccessCBK"/>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownloadTemplate">模板下载</el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :key="tableKey"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;">
      <el-table-column :label="$t('userTable.id')" align="center" width="65">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="出单日期" width="" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.insuranceDate | parseTime('{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="保险公司" width="" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.insuranceCompany }}</span>
        </template>
      </el-table-column>
      <el-table-column label="保单号" width="" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.policyNo }}</span>
        </template>
      </el-table-column>
      <el-table-column label="车牌号" width="" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.plateNo }}</span>
        </template>
      </el-table-column>
      <el-table-column label="车主" width="" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.carOwner }}</span>
        </template>
      </el-table-column>
      <el-table-column label="业务员" width="" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.employeeName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="业务员工号" width="" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.employeeNo }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商业险" width="" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.commercialInsurancePremium }}</span>
        </template>
      </el-table-column>
      <el-table-column label="佣金比例" width="" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.commercialCommissionRate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="交强险" width="" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.compulsoryInsurancePremium }}</span>
        </template>
      </el-table-column>
      <el-table-column label="佣金比例" width="" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.compulsoryCommissionRate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="应发佣金" width="" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.commissionPayable }}</span>
        </template>
      </el-table-column>
      <el-table-column label="实发佣金" width="" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.commissionActual }}</span>
        </template>
      </el-table-column>
      <el-table-column label="应缴个税" width="" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.commissionTax }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('table.actions')" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <router-link :to="'/commission/share/'+scope.row.id">
            <el-button size="mini" type="success">缴税</el-button>
          </router-link>
          <el-button type="primary" size="mini" style="margin-left:10px;" @click="handleUpdate(scope.row)">{{ $t('table.edit') }}</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">{{ $t('table.delete') }}</el-button>

        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.current" :limit.sync="listQuery.size" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="commissionCarForm" :model="commissionCarForm" :rules="rules" label-width="150px" class="commissionCarForm" style="width: 500px; margin-left:50px;">
        <el-form-item label="保险公司" prop="insuranceCompany">
          <el-input v-model="commissionCarForm.insuranceCompany" placeholder="输入保险公司名称" maxlength="100"/>
        </el-form-item>
        <el-form-item label="保单号" prop="policyNo">
          <el-input v-model="commissionCarForm.policyNo" placeholder="输入保单号" maxlength="100"/>
        </el-form-item>
        <el-form-item label="车牌号" prop="plateNo">
          <el-input v-model="commissionCarForm.plateNo" placeholder="输入车牌号" maxlength="10"/>
        </el-form-item>
        <el-form-item label="车主姓名" prop="carOwner">
          <el-input v-model="commissionCarForm.carOwner" placeholder="输入车主姓名" maxlength="11"/>
        </el-form-item>
        <el-form-item label="商业险保费" prop="commercialInsurancePremium">
          <el-input v-model="commissionCarForm.commercialInsurancePremium" placeholder="输入商业险保费"/>
        </el-form-item>
        <el-form-item label="商业险佣金比例" prop="commercialCommissionRate">
          <el-input v-model="commissionCarForm.commercialCommissionRate" placeholder="输入商业险佣金比例"/>
        </el-form-item>
        <el-form-item label="交强险保费" prop="compulsoryInsurancePremium">
          <el-input v-model="commissionCarForm.compulsoryInsurancePremium" placeholder="输入交强险保费"/>
        </el-form-item>
        <el-form-item label="交强险佣金比例" prop="compulsoryCommissionRate">
          <el-input v-model="commissionCarForm.compulsoryCommissionRate" placeholder="输入交强险佣金比例"/>
        </el-form-item>
        <el-form-item label="应发佣金" prop="commissionPayable">
          <el-input v-model="commissionCarForm.commissionPayable" placeholder="输入应发佣金"/>
        </el-form-item>
        <el-form-item label="实发佣金" prop="commissionActual">
          <el-input v-model="commissionCarForm.commissionActual" placeholder="输入实发佣金"/>
        </el-form-item>
        <el-form-item label="出单日期" prop="insuranceDate">
          <el-date-picker
            v-model="commissionCarForm.insuranceDate"
            style="width:100%;"
            type="date"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            placeholder="请选择出单日期"/>
        </el-form-item>
        <el-form-item label="业务员工号" prop="employeeNo">
          <el-input v-model="commissionCarForm.employeeNo" placeholder="输入业务员工号"/>
        </el-form-item>
        <el-form-item label="业务员姓名" prop="employeeName">
          <el-input v-model="commissionCarForm.employeeName" placeholder="输入业务员姓名"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{ $t('table.cancel') }}</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">{{ $t('table.confirm') }}</el-button>
        <el-button v-else type="primary" @click="updateData">{{ $t('table.confirm') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchCommissionCarList, createCommissionCar, deleteCommissionCar, updateCommissionCar, updateCommissionCarStatus } from '@/api/finance/commission_car'
import waves from '@/directive/waves' // 水波纹指令
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import FileUpload from '@/components/Upload/uploadFile'

export default {
  name: 'CommissionCarTable',
  components: { Pagination, FileUpload },
  directives: {
    waves
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: 'success',
        2: 'danger',
        0: 'info'
      }
      return statusMap[status]
    },
    statusNameFilter(status) {
      const statusNameMap = {
        1: '已确认',
        2: '未通过',
        0: '待审核'
      }
      return statusNameMap[status]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        current: 1,
        size: 20,
        employeeName: '',
        employeeNo: '',
        policyNo: '',
        startDate: '',
        endDate: ''
      },
      statusOption: [
        { label: '已确认', key: '1' },
        { label: '待审核', key: '0' },
        { label: '未通过', key: '2' }
      ],
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加'
      },
      commissionCarForm: {
        id: '',
        insuranceCompany: '',
        policyNo: '',
        plateNo: '',
        carOwner: '',
        commercialInsurancePremium: '',
        commercialCommissionRate: '',
        compulsoryInsurancePremium: '',
        compulsoryCommissionRate: '',
        commissionPayable: '',
        commissionActual: '',
        insuranceDate: '',
        employeeId: '',
        employeeNo: '',
        employeeName: ''
      },
      rules: {
        insuranceCompany: [
          { required: true, message: '请输入保险公司名称', trigger: 'blur' }
        ],
        policyNo: [
          { required: true, message: '请输入保单号', trigger: 'blur' }
        ],
        plateNo: [
          { required: true, message: '车牌号', trigger: 'blur' }
        ],
        carOwner: [
          { required: true, message: '请输入车主姓名', trigger: 'blur' }
        ],
        commercialInsurancePremium: [
          { required: true, message: '请输入商业险保费', trigger: 'blur' }
        ],
        commercialCommissionRate: [
          { required: true, message: '请输入商业险佣金比例', trigger: 'blur' }
        ],
        compulsoryInsurancePremium: [
          { required: true, message: '请输入交强险保费', trigger: 'blur' }
        ],
        compulsoryCommissionRate: [
          { required: true, message: '请输入交强险佣金比例', trigger: 'blur' }
        ],
        commissionPayable: [
          { required: true, message: '请输入应发佣金', trigger: 'blur' }
        ],
        commissionActual: [
          { required: true, message: '请输入实发佣金', trigger: 'blur' }
        ],
        insuranceDate: [
          { required: true, message: '请输入投保日期', trigger: 'blur' }
        ],
        employeeNo: [
          { required: true, message: '请输入业务员工号', trigger: 'blur' }
        ],
        employeeName: [
          { required: true, message: '请输入业务员姓名', trigger: 'blur' }
        ]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    fileSuccessCBK(arr) {
      this.getList()
    },
    getList() {
      this.listLoading = true
      fetchCommissionCarList(this.listQuery).then(response => {
        this.list = response.data
        this.total = response.count
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.current = 1
      this.getList()
    },
    resetCommissionCarForm() {
      this.commissionCarForm = {
        id: '',
        insuranceCompany: '',
        policyNo: '',
        plateNo: '',
        carOwner: '',
        commercialInsurancePremium: '',
        commercialCommissionRate: '',
        compulsoryInsurancePremium: '',
        compulsoryCommissionRate: '',
        commissionPayable: '',
        commissionActual: '',
        insuranceDate: '',
        employeeId: '',
        employeeNo: '',
        employeeName: ''
      }
    },
    handleCreate() {
      this.resetCommissionCarForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['commissionCarForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['commissionCarForm'].validate(valid => {
        if (valid) {
          createCommissionCar(this.commissionCarForm).then(() => {
            this.dialogFormVisible = false
            this.handleFilter()
            this.$message({
              message: '创建成功',
              type: 'success'
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.commissionCarForm = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['commissionCarForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['commissionCarForm'].validate(valid => {
        if (valid) {
          updateCommissionCar(this.commissionCarForm).then(() => {
            for (const v of this.list) {
              if (v.id === this.commissionCarForm.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.commissionCarForm)
                break
              }
            }
            this.dialogFormVisible = false
            this.$message({
              message: '更新成功',
              type: 'success'
            })
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm(
        '此操作将永久删除该佣金数据：' + row.policyNo + ', 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          this.listLoading = true
          deleteCommissionCar(row.id).then(() => {
            this.listLoading = false
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    handleModifyStatus(row, status) {
      this.listLoading = true
      updateCommissionCarStatus(row.id, status).then(() => {
        this.listLoading = false
        row.userStatus = status
        this.$message({
          message: '状态修改成功',
          type: 'success'
        })
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = [
          '保险公司',
          '保单号',
          '车牌号',
          '车主',
          '商业险保费',
          '商业险佣金比例',
          '交强险保费',
          '交强险佣金比例',
          '应发佣金',
          '实发佣金',
          '投保日期',
          '业务员工号',
          '业务员姓名'
        ]
        const filterVal = [
          'insuranceCompany',
          'policyNo',
          'plateNo',
          'carOwner',
          'commercialInsurancePremium',
          'commercialCommissionRate',
          'compulsoryInsurancePremium',
          'compulsoryCommissionRate',
          'commissionPayable',
          'commissionActual',
          'insuranceDate',
          'employeeNo',
          'employeeName'
        ]
        const data = this.formatJson(filterVal, this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '车险佣金列表'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === 'createTime') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      )
    },
    handleDownloadTemplate() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = [
          '保险公司',
          '保单号',
          '车牌号',
          '车主',
          '商业险保费',
          '商业险佣金比例',
          '交强险保费',
          '交强险佣金比例',
          '应发佣金',
          '投保日期',
          '业务员工号',
          '业务员姓名'
        ]
        const data = {}
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '批量佣金模板'
        })
        this.downloadLoading = false
      })
    }
  }
}
</script>
